package org.smartboot.socket.client;

import org.smartboot.socket.common.ChatMessage;
import org.smartboot.socket.common.ChatProtocal;
import org.smartboot.socket.transport.AioQuickClient;
import org.smartboot.socket.transport.AioSession;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Scanner;

/**
 * @author laoliu
 * @since 1.0
 */
public class ChatClient {
    private static byte[] dumpObjToByte(ChatMessage msg)throws IOException{
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutput = new ObjectOutputStream(byteArrayOutputStream);
        objectOutput.writeObject(msg);
        byte[] data = byteArrayOutputStream.toByteArray();
        return data;
    }
    public static void sendMsg(ChatMessage msg,AioSession session){
        try {
            byte []b2=dumpObjToByte(msg);
            session.writeBuffer().writeInt(b2.length);
            session.writeBuffer().write(b2);
            session.writeBuffer().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        AioQuickClient<ChatMessage> consumer = new AioQuickClient<>("localhost", 9999,new ChatProtocal(),new ChatClientProcessor() );
        AioSession session = consumer.start();
        Scanner in=new Scanner(System.in);
        System.out.println("请输入你的名字：");
        String name=in.next();
        ChatMessage cm=new ChatMessage(name,ChatMessage.TO._LOGIN.toString(),name+"上线了");
        sendMsg(cm,session);
        while(true){
            System.out.println("开始聊天,发给谁：");
            String toName=in.next();
            System.out.println("内容：");
            String message=in.next();
            cm=new ChatMessage(name,toName,message);
            sendMsg(cm,session);
        }
    }
}
